package com.hq.talk.presenter.impl;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.hq.lib_comview.common.code.CodeStatus;
import com.hq.lib_comview.common.code.ReturnCode;
import com.hq.lib_comview.common.utils.NetUtil;
import com.hq.lib_comview.common.utils.ToastUtil;
import com.hq.talk.R;
import com.hq.talk.common.ConstantTag;
import com.hq.talk.common.Session;
import com.hq.talk.http.BaseCallback;
import com.hq.talk.http.CallManager;
import com.hq.talk.http.HandleRetCode;
import com.hq.talk.http.Http;
import com.hq.talk.http.ResponseData;
import com.hq.talk.http.request.APIService;
import com.hq.talk.model.CompanyModel;
import com.hq.talk.model.UserInfoModel;
import com.hq.talk.model.WorkModel;
import com.hq.talk.presenter.GeneralPresenter;
import com.hq.talk.presenter.IViewController;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;

/**
 * 描述 ：处理用户信息
 * 作者 ：hq
 * 时间 ：2017/8/8 22:01
 */
public class UserPresenter extends GeneralPresenter {

    private Context mContext;
    private IViewController mView;
    private APIService mService;
    private UMShareAPI mShareAPI;
    private String openId = "";
    private String token = "";

    @Override
    public Object getCacheData() {
        return null;
    }

    @Override
    public void attachView(IViewController view) {
        this.mView = view;
        mContext = getContext(view);
        mService = Http.getUserService(mContext);
        mShareAPI = UMShareAPI.get(mContext);
    }

    /**
     * 获得用户登录信息
     */
    public void login(String mPhone, String mpw) {
        if (!NetUtil.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, mContext.getString(R.string.no_net_work));
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, mContext.getString(R.string.data_loading));
        Call<ResponseData<UserInfoModel>> call = mService.login(mPhone, mpw);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<UserInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseData<UserInfoModel>> call, Response<ResponseData<UserInfoModel>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<UserInfoModel> res = response.body();
                    if (res.getCode() == ReturnCode.SUCCESS) {
                        UserInfoModel userModel = res.getData();
                        if (null != userModel) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                            mView.updateViewWithTag(userModel, ConstantTag.Login.LOGIN_SUCCESS);
                            return;
                        }
                    } else {
                        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
                        HandleRetCode.handler(mContext, res, true, mContext.getString(R.string.login_fail));
                        return;
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.login_fail));
            }

            @Override
            public void onFailure(Call<ResponseData<UserInfoModel>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.login_fail));
            }
        });
    }

    /**
     * 获取短信验证码
     */
    public void sendCode(String mPhone, int type) {
        if (!NetUtil.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, mContext.getString(R.string.no_net_work));
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, mContext.getString(R.string.data_loading));
        Call<ResponseData> call = mService.getSms(mPhone, type);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData res = response.body();
                    if (res.getCode() == ReturnCode.SUCCESS) {
                        mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                        return;
                    } else {
                        mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
                        HandleRetCode.handler(mContext, res, true, mContext.getString(R.string.get_data_fail));
                        return;
                    }
                }
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.get_data_fail));
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.get_data_fail));
            }
        });
    }

    /**
     * 注册
     */
    public void register(String mPhone, String code, String pw, String name) {
        if (!NetUtil.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, mContext.getString(R.string.no_net_work));
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, mContext.getString(R.string.data_loading));
        Call<ResponseData<UserInfoModel>> call = mService.register(mPhone, code, pw, name, "2", "1");
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<UserInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseData<UserInfoModel>> call, Response<ResponseData<UserInfoModel>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<UserInfoModel> res = response.body();
                    if (res.getCode() == ReturnCode.SUCCESS) {
                        UserInfoModel userModel = res.getData();
                        if (null != userModel) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                            mView.updateViewWithTag(userModel, ConstantTag.Login.REGISTER_SUCCESS);
                            return;
                        }
                    } else {
                        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
                        HandleRetCode.handler(mContext, res, true, mContext.getString(R.string.register_fail));
                        return;
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.register_fail));
            }

            @Override
            public void onFailure(Call<ResponseData<UserInfoModel>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.register_fail));
            }
        });
    }

    /**
     * 找回密码
     */
    public void findPw(String mPhone, String code, String mpw) {
        if (!NetUtil.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, mContext.getString(R.string.no_net_work));
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, mContext.getString(R.string.data_loading));
        Call<ResponseData> call = mService.resetPw(mPhone, code, mpw);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData res = response.body();
                    if (res.getCode() == ReturnCode.SUCCESS) {
                        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                        mView.updateViewWithTag(res.getCode(), ConstantTag.Login.FIND_PW_SUCCESS);
                        return;
                    } else {
                        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
                        HandleRetCode.handler(mContext, res, true, mContext.getString(R.string.ask_data_fail));
                        return;
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.ask_data_fail));
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, mContext.getString(R.string.ask_data_fail));
            }
        });
    }

    /**
     * 查询我的工作技能
     */
    public void searchMyWork() {
        if (!NetUtil.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, "");
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, "");
        Call<ResponseData<List<WorkModel>>> call = mService.searchMyWork(Session.getUserId(), Session.getUserToken());
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<List<WorkModel>>>() {
            @Override
            public void onResponse(Call<ResponseData<List<WorkModel>>> call, Response<ResponseData<List<WorkModel>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<List<WorkModel>> res = response.body();
                    if (res.getCode() == ReturnCode.SUCCESS) {
                        List<WorkModel> works = res.getData();
                        if (null != works) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                            mView.updateViewWithTag(works, ConstantTag.User.MY_WORK);
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
            }

            @Override
            public void onFailure(Call<ResponseData<List<WorkModel>>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
            }
        });
    }

    @Override
    public void detachView() {

    }

    /**
     * 处理三方登录
     */
    private void bindOtherLogin(){

    }

    /**
     * QQ授权登录
     */
    public void qqAuth() {
        SHARE_MEDIA platform = SHARE_MEDIA.QQ;
        checkAuth(platform);
    }

    /**
     * 微信授权登录
     */
    public void wxAuth() {
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
        boolean install = mShareAPI.isInstall((Activity) mContext, platform);
        if (install) {
            checkAuth(platform);
        } else {
            ToastUtil.showToast(mContext,"没有安装微信客户端");
        }
    }

    /**
     * 微博授权登录
     */
    public void wbAuth() {
        SHARE_MEDIA platform = SHARE_MEDIA.SINA;
//        Config.REDIRECT_URL = Constants.Sina.REDIRECT_URL;
        checkAuth(platform);
    }

    /*
     *删除授权
     */
    private void delAuth(SHARE_MEDIA platform, boolean isReAuth) {
        mShareAPI.deleteOauth((Activity) mContext, platform, delAuthListener);
    }

    private void checkAuth(SHARE_MEDIA platform) {
        switch (platform) {
            case QQ:
                mShareAPI.doOauthVerify((Activity) mContext, platform, authListener);
                break;
            case WEIXIN:
                mShareAPI.doOauthVerify((Activity) mContext, platform, authListener);
                break;
            case SINA:
                //未授权则先去授权
//                if (!mShareAPI.isAuthorize(LoginActivity.this, platform)) {
                mShareAPI.doOauthVerify((Activity) mContext, platform, authListener);
//                } else {
//                    //已授权则获取用户数据
//                    mShareAPI.getPlatformInfo(LoginActivity.this, platform, getInfoListener);
//                }
                break;
        }
    }

    /**
     * 授权回调
     */
    private UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            ToastUtil.showToast(mContext,"开始授权");
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            ToastUtil.showToast(mContext,"授权成功");
            for (Map.Entry<String, String> entry : map.entrySet()) {
                Log.d("LoginAty+++++", entry.getKey() + ":" + entry.getValue());
            }
            mShareAPI.getPlatformInfo((Activity) mContext, share_media, getInfoListener);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            Log.d("授权",i+"------"+throwable.getMessage());
            ToastUtil.showToast(mContext,"授权失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            ToastUtil.showToast(mContext,"取消授权");
        }
    };

    /**
     * 获取用户资料
     */
    private UMAuthListener getInfoListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            ToastUtil.showToast(mContext,"开始读取用户信息");
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            ToastUtil.showToast(mContext,"读取用户信息成功");
            if (map != null) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    Log.d("LoginAty----", entry.getKey() + ":" + entry.getValue());
                }
                switch (share_media) {
                    case QQ: {
                        openId = map.get("openid");
                        token = map.get("accessToken");
                        break;
                    }
                    case WEIXIN: {
                        openId = map.get("openid");
                        token = map.get("accessToken");
                        break;
                    }
                    case SINA: {
                        openId = map.get("uid");
                        token = map.get("accessToken");
                        break;
                    }
                }
                bindOtherLogin();
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            ToastUtil.showToast(mContext,"读取用户信息失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            ToastUtil.showToast(mContext,"读取用户信息取消");
        }
    };

    /**
     *  删除授权
     */
    private UMAuthListener delAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            ToastUtil.showToast(mContext,"开始删除");
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            ToastUtil.showToast(mContext,"开始成功");
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            ToastUtil.showToast(mContext,"开始失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            ToastUtil.showToast(mContext,"取消删除");
        }
    };
}
